import { Component, OnInit } from '@angular/core';
import { map, takeUntil } from 'rxjs/operators';
import { NzMessageService } from 'ng-zorro-antd';
import { ActivatedRoute, Router } from '@angular/router';
import { Subject } from 'rxjs';
import { Singer, SingerDetail, Song } from '@services/data-types/common.type';
import { SongService } from '@services/song.service';
import { BatchActionsService } from '@store/batch-actions.service';
import { select, Store } from '@ngrx/store';
import { getCurrentSong, getPlayer } from '@store/selectors/player.selector';
import { findIndex } from '@utils/array';
import { AppStoreModule } from '@store/index';
import { MemberService } from '@services/member.service';
import { ShareInfo } from '@store/reducers/member.reducer';


@Component({
  selector: 'app-singer-detail',
  templateUrl: './singer-detail.component.html',
  styleUrls: ['./singer-detail.component.less']
})
export class SingerDetailComponent implements OnInit {
  currentIndex: number;
  currentSong: Song;
  singerInfo: SingerDetail;
  similarSingers: Singer[];
  hasLiked = false;
  private destroy$ = new Subject<void>();
  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private songServe: SongService,
    private store$: Store<AppStoreModule>,
    private nzMessageServe: NzMessageService,
    private memberService: MemberService,
    private batchActionsService: BatchActionsService
  ) {
    this.route.data.pipe(map(res => res.singerDetail)).subscribe(([singerInfo, similarSingers]) => {
      this.singerInfo = singerInfo;
      this.similarSingers = similarSingers;
    });
  }

  ngOnInit() {
    this.listenCurrentSong();
  }
  private listenCurrentSong() {
    this.store$.pipe(select(getPlayer), select(getCurrentSong), takeUntil(this.destroy$)).subscribe(song => {
      this.currentSong = song;
      if (song) {
        this.currentIndex = findIndex(this.singerInfo.hotSongs, song);
      } else {
        this.currentIndex = -1;
      }
    });
  }
  // 收藏歌曲
  onLikeSong(songs: Song | Song[]) {
    // 判断是一首歌曲还是一组歌曲
    let ids = '';
    if (Array.isArray(songs)) {
      ids = songs.map(song => song.id).join(',');
    } else {
      ids = songs.id.toString();
    }
    this.batchActionsService.likeSong(ids);
  }
  // 收藏歌手
  onLikeSinger(id: string) {
    let typeInfo = {
      type: 1,
      msg: '已收藏'
    };
    if (this.hasLiked) {
      typeInfo = {
        type: 2,
        msg: '取消收藏'
      };
    }
    this.memberService.likeSinger(id, typeInfo.type).subscribe(() => {
      this.hasLiked = !this.hasLiked;
      this.alertMessage('success', typeInfo.msg);
    }, error => {
      this.alertMessage('error', error.msg || typeInfo.msg);
    });
  }
  // 分享歌曲
  onShareSong(song: Song, type = 'song') {
    const txt = this.makeTxt('歌曲', song.name, song.ar);
    const info: ShareInfo = {id: song.id.toString(), type, txt};
    this.batchActionsService.setShareInfo(info);
  }
  // 添加歌曲到歌单
  onAddSong(song: Song, isPlay = false) {
    if (!this.currentSong || song.id !== this.currentSong.id) {
      this.songServe.getSongList(song).subscribe(list => {
        // 如果当前歌曲没有url，就不再执行insertSong这个Action
        if (list.length) {
          this.batchActionsService.insertSong(list[0], isPlay);
        } else {
          this.alertMessage('warning', '无播放源url');
        }
      });
    }
  }
  // 添加歌曲列表到歌单
  onAddSongs(songs: Song[], isPlay = false) {
    this.songServe.getSongList(songs).subscribe(list => {
      if (list.length) {
        if (isPlay) {
          this.batchActionsService.selectPlayList({ list, index: 0 });
        } else {
          this.batchActionsService.insertSongList(list);
        }
      }
    });
  }
  private makeTxt(type: string, name: string, makeBy: string | Singer[]): string {
    let needText = '';
    if (Array.isArray(makeBy)) {
      needText = makeBy.map(item => item.name).join('/');
    } else {
      needText = makeBy;
    }
    return `${type}: ${name} -- ${needText}`;
  }
  private alertMessage(type: string, msg: string) {
    this.nzMessageServe.create(type, msg);
  }
}
